[[...path]].page.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import React, { useEffect } from 'react';
  2. import type { IUserHasId, IPagePopulatedToShowRevision } from '@growi/core';
  3. import type {
  4. GetServerSideProps, GetServerSidePropsContext,
  5. } from 'next';
  6. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  7. import Head from 'next/head';
  8. import superjson from 'superjson';
  9. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  10. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  11. import GrowiContextualSubNavigationSubstance from '~/components/Navbar/GrowiContextualSubNavigation';
  12. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  13. import { ShareLinkPageView } from '~/components/ShareLinkPageView';
  14. import { SupportedAction, SupportedActionType } from '~/interfaces/activity';
  15. import type { CrowiRequest } from '~/interfaces/crowi-request';
  16. import type { RendererConfig } from '~/interfaces/services/renderer';
  17. import type { IShareLinkHasId } from '~/interfaces/share-link';
  18. import type { PageDocument } from '~/server/models/page';
  19. import {
  20. useCurrentUser, useRendererConfig, useIsSearchPage, useCurrentPathname,
  21. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useIsContainerFluid,
  22. } from '~/stores/context';
  23. import { useCurrentPageId, useIsNotFound, useSWRMUTxCurrentPage } from '~/stores/page';
  24. import loggerFactory from '~/utils/logger';
  25. import type { NextPageWithLayout } from '../_app.page';
  26. import {
  27. getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig, CommonProps, skipSSR,
  28. } from '../utils/commons';
  29. const logger = loggerFactory('growi:next-page:share');
  30. type Props = CommonProps & {
  31. shareLinkRelatedPage?: IShareLinkRelatedPage,
  32. shareLink?: IShareLinkHasId,
  33. isNotFound: boolean,
  34. isExpired: boolean,
  35. disableLinkSharing: boolean,
  36. isSearchServiceConfigured: boolean,
  37. isSearchServiceReachable: boolean,
  38. isSearchScopeChildrenAsDefault: boolean,
  39. drawioUri: string | null,
  40. rendererConfig: RendererConfig,
  41. skipSSR: boolean,
  42. };
  43. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  44. superjson.registerCustom<IShareLinkRelatedPage, string>(
  45. {
  46. isApplicable: (v): v is IShareLinkRelatedPage => {
  47. return v != null
  48. && v.toObject != null
  49. && v.lastUpdateUser != null
  50. && v.creator != null
  51. && v.revision != null;
  52. },
  53. serialize: (v) => { return superjson.stringify(v.toObject()) },
  54. deserialize: (v) => { return superjson.parse(v) },
  55. },
  56. 'IShareLinkRelatedPageTransformer',
  57. );
  58. // GrowiContextualSubNavigation for shared page
  59. // get page info from props not to send request 'GET /page' from client
  60. type GrowiContextualSubNavigationForSharedPageProps = {
  61. page?: IPagePopulatedToShowRevision,
  62. isLinkSharingDisabled: boolean,
  63. }
  64. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  65. const { page, isLinkSharingDisabled } = props;
  66. return (
  67. <div data-testid="grw-contextual-sub-nav">
  68. <GrowiContextualSubNavigationSubstance currentPage={page} isLinkSharingDisabled={isLinkSharingDisabled}/>
  69. </div>
  70. );
  71. };
  72. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  73. useCurrentPathname(props.shareLink?.relatedPage.path);
  74. useIsSearchPage(false);
  75. useIsNotFound(props.isNotFound);
  76. useShareLinkId(props.shareLink?._id);
  77. useCurrentPageId(props.shareLink?.relatedPage._id);
  78. useCurrentUser(props.currentUser);
  79. useRendererConfig(props.rendererConfig);
  80. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  81. useIsSearchServiceReachable(props.isSearchServiceReachable);
  82. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  83. useIsContainerFluid(props.isContainerFluid);
  84. const { trigger: mutateCurrentPage, data: currentPage } = useSWRMUTxCurrentPage();
  85. useEffect(() => {
  86. if (!props.skipSSR) {
  87. return;
  88. }
  89. if (props.shareLink?.relatedPage._id != null && !props.isNotFound) {
  90. mutateCurrentPage();
  91. }
  92. }, [mutateCurrentPage, props.isNotFound, props.shareLink?.relatedPage._id, props.skipSSR]);
  93. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(props.shareLinkRelatedPage);
  94. const pagePath = props.shareLinkRelatedPage?.path ?? '';
  95. const title = generateCustomTitleForPage(props, pagePath);
  96. return (
  97. <>
  98. <Head>
  99. <title>{title}</title>
  100. </Head>
  101. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  102. <header className="py-0 position-relative">
  103. <GrowiContextualSubNavigationForSharedPage page={currentPage ?? props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />
  104. </header>
  105. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  106. <ShareLinkPageView
  107. pagePath={pagePath}
  108. rendererConfig={props.rendererConfig}
  109. page={currentPage ?? props.shareLinkRelatedPage}
  110. shareLink={props.shareLink}
  111. isExpired={props.isExpired}
  112. disableLinkSharing={props.disableLinkSharing}
  113. />
  114. </div>
  115. </>
  116. );
  117. };
  118. SharedPage.getLayout = function getLayout(page) {
  119. return (
  120. <>
  121. <DrawioViewerScript />
  122. <ShareLinkLayout>{page}</ShareLinkLayout>
  123. </>
  124. );
  125. };
  126. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  127. const req: CrowiRequest = context.req as CrowiRequest;
  128. const { crowi } = req;
  129. const { configManager, searchService } = crowi;
  130. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  131. props.isSearchServiceConfigured = searchService.isConfigured;
  132. props.isSearchServiceReachable = searchService.isReachable;
  133. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  134. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  135. props.rendererConfig = {
  136. isSharedPage: true,
  137. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  138. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  139. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  140. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  141. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  142. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  143. // XSS Options
  144. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  145. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  146. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  147. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  148. highlightJsStyleBorder: configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  149. };
  150. }
  151. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  152. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  153. props._nextI18Next = nextI18NextConfig._nextI18Next;
  154. }
  155. function getAction(props: Props): SupportedActionType {
  156. let action: SupportedActionType;
  157. if (props.isExpired) {
  158. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  159. }
  160. else if (props.shareLink == null) {
  161. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  162. }
  163. else {
  164. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  165. }
  166. return action;
  167. }
  168. async function addActivity(context: GetServerSidePropsContext, action: SupportedActionType): Promise<void> {
  169. const req: CrowiRequest = context.req as CrowiRequest;
  170. const parameters = {
  171. ip: req.ip,
  172. endpoint: req.originalUrl,
  173. action,
  174. user: req.user?._id,
  175. snapshot: {
  176. username: req.user?.username,
  177. },
  178. };
  179. await req.crowi.activityService.createActivity(parameters);
  180. }
  181. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  182. const req = context.req as CrowiRequest<IUserHasId & any>;
  183. const { crowi, params } = req;
  184. const result = await getServerSideCommonProps(context);
  185. if (!('props' in result)) {
  186. throw new Error('invalid getSSP result');
  187. }
  188. const props: Props = result.props as Props;
  189. try {
  190. const ShareLinkModel = crowi.model('ShareLink');
  191. const shareLink = await ShareLinkModel.findOne({ _id: params.linkId }).populate('relatedPage');
  192. if (shareLink == null) {
  193. props.isNotFound = true;
  194. }
  195. else {
  196. props.isNotFound = false;
  197. props.skipSSR = await skipSSR(shareLink.relatedPage);
  198. props.shareLinkRelatedPage = await shareLink.relatedPage.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  199. props.isExpired = shareLink.isExpired();
  200. props.shareLink = shareLink.toObject();
  201. }
  202. }
  203. catch (err) {
  204. logger.error(err);
  205. }
  206. injectServerConfigurations(context, props);
  207. await injectNextI18NextConfigurations(context, props);
  208. await addActivity(context, getAction(props));
  209. return {
  210. props,
  211. };
  212. };
  213. export default SharedPage;